var si, st, body = document.body,
    loading_main, isRemove;

function get_screenPx() {
    this.w = Number(window.innerWidth ? window.innerWidth : document.documentElement.clientWidth);
    this.h = Number(window.innerHeight ? window.innerHeight : document.documentElement.clientHeight);
    this.styleID = document.getElementById("styleID");
}

get_screenPx.prototype = {
    method_screenPx: function() {
        if (this.w > 750) {
            if (privateFun.isAndroid() && !privateFun.isPad()) {
                this.w = parseInt(this.w / 2.3671); //处理Retina屏幕
                this.styleID.innerHTML = 'html {font-size: ' + parseFloat(this.w / 7.5) + 'px;}';
            } else {
                this.styleID.innerHTML = 'html {font-size: ' + parseFloat(this.w / 19,2) + 'px;}';
            }
        } else {
            this.styleID.innerHTML = 'html {font-size: ' + parseFloat(this.w / 7.5) + 'px;}';
        }
    }
}

var privateFun = {
    logic_screenPx: function() {
        var screenPx = new get_screenPx();
        screenPx.method_screenPx();

        this.clear_NewObj(screenPx);
        return;
    },
    clearTime: function(v) {
        if (v === "setTimeout") {
            clearTimeout(st);
        } else if (v === "setInterval") {
            clearInterval(si);
        }
        return;
    },

    //清除实例NEW对象
    clear_NewObj: function(obj) {
        for (var key in obj) {
            delete obj[key];
        }
    },
    //以下存放单方法
    isAndroid: function() {
        var u = navigator.userAgent;
        var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
        var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
        if (isiOS) {
            return "ios";
        }
        if (isAndroid) {
            return "android";
        }
        return false;
    },
    isPad: function() {
        var u = navigator.userAgent;
        var iipad = u.indexOf('pad') > -1 || u.indexOf('iPad') > -1; //android终端
        return iipad;
    },
    //针对IE浏览器兼容，做CLASS添加
    addClass: function(obj, cls) {
        var obj_class = obj.className; //获取 class 内容.
        var blank = (obj_class != '') ? ' ' : ''; //判断获取到的 class 是否为空, 如果不为空在前面加个'空格'.
        var added = obj_class + blank + cls; //组合原来的 class 和需要添加的 class.
        obj.className = added; //替换原来的 class.
    },
    //针对IE浏览器兼容，做CLASS移除
    removeClass: function(obj, cls) {
        var obj_class = ' ' + obj.className + ' '; //获取 class 内容, 并在首尾各加一个空格. ex) 'abc        bcd' -> ' abc        bcd '
        obj_class = obj_class.replace(/(\s+)/gi, ' '); //将多余的空字符替换成一个空格. ex) ' abc        bcd ' -> ' abc bcd '
        var removed = obj_class.replace(' ' + cls + ' ', ' '); //在原来的 class 替换掉首尾加了空格的 class. ex) ' abc bcd ' -> 'bcd '
        removed = removed.replace(/(^\s+)|(\s+$)/g, ''); //去掉首尾空格. ex) 'bcd ' -> 'bcd'
        obj.className = removed; //替换原来的 class.
    },
    //基于JQUERY-AJAX，并入等待loading效果。
    // ajax: function (options) {
    //     var _this = this;
    //     var options = options || {};
    //     _this.loadingNow("loading");
    //     $.ajax({
    //         url: options.url,
    //         type: options.type || 'GET',
    //         dataType: options.dataType || 'JSON',
    //         data: options.data,
    //         cache: options.cache === false ? false : true,
    //         async: options.async === false ? false : true,
    //         processData: options.processData === false ? false : true,
    //         contentType: options.processData === false ? false : "application/x-www-form-urlencoded; charset=UTF-8",
    //         success: function (data) {
    //             _this.loadingNow("close");
    //             if (data.statusCode < 0 && data.desc) {
    //                 _this.showLayer(data.desc, "error");
    //                 return;
    //             }
    //             options.success(data);
    //         }, error: function (e) {
    //             _this.loadingNow("close");
    //             _this.showLayer("服务返回错误", "error");
    //         }
    //     });
    // },
    //原生ajax
    originalAjax: function(options) {
        options = options || {};
        options.type = options.type || "GET";
        options.dataType = options.dataType || "json";
        options.data = options.data || {};
        options.asyn = options.asyn || true;
        var xhr;
        //创建 - 第一步
        if (window.XMLHttpRequest) {
            xhr = new XMLHttpRequest();
        } else if (window.ActiveObject) { //IE6及以下
            xhr = new ActiveXObject('Microsoft.XMLHTTP');
        }
        //连接 和 发送 - 第二步
        if (options.type == "GET") {
            xhr.open("GET", "http://xt.yundapian.com" + options.url + "?" + options.data, options.asyn);
            xhr.send(null);
        } else if (options.type == "POST") {
            xhr.open("POST", "http://xt.yundapian.com" + options.url, options.asyn);
            //设置表单提交时的内容类型
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            xhr.send(options.data);
        }
        //接收 - 第三步
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4) {
                var status = xhr.status;
                if (status >= 200 && status < 300 || status == 304) {
                    options.success && options.success(xhr.responseText, xhr.responseXML);
                } else {
                    options.error && options.error(status);
                }
            }
        }
    },
    //loading效果...，传入start:close/loading，time:停留时间默认loading:1000、close:1500。
    loadingNow:function(start, time, callback) {
        var loading_main;
        var _this = this;
        var time = time ? time : (start === "loading") ? 0 : 500;

        if (!isRemove) {
            isRemove = {
                isClose_i: 0,
                isOpen: function () {
                    isRemove.isClose_i++;
                },
                isClose: function () {
                    isRemove.isClose_i--;
                    if(isRemove.isClose_i !== 0){
                        isRemove.isClose_i = 0;
                    }
                }
            }
        }

        if (!loading_main) {
            loading_main = document.createElement("div");
            loading_main.id = "loading_main";
            var effect_1 = document.createElement("div");
            effect_1.className = "effect_1";
            effect_1.innerHTML = "<span></span><span></span><span></span>";
            loading_main.appendChild(effect_1);
            body.appendChild(loading_main);
        }

        function isShow(v) {
            loading_main.style.display = v;
        }

        if (start === "close") {
            clearTimeout(st);
            isRemove.isClose();
            if (isRemove.isClose_i === 0) {
                setTimeout(function() {
                    loading_main.remove();
                }, time);
            }
        }
        if (start === "loading") {
            isRemove.isOpen();
            st = setTimeout(function() {
                isShow("block")
            }, time);
        }
    },
    //错误提示框
    showLayer: function(txt, type) {
        var layer = document.createElement("div");
        layer.id = "layer";
        body.appendChild(layer);
        if (!layer.getAttribute("class")) {
            layer.innerHTML = txt;
            switch (type) {
                case "error":
                    layer.setAttribute("class", "error");
                    break;
            }
            layer.style.marginLeft = ((layer.offsetWidth / 2) * -1) + "px";
            layer.style.marginTop = ((layer.offsetHeight / 2) * -1) + "px";
            setTimeout(function() {
                layer.removeAttribute("class");
                layer.remove();
            }, 1800);
        }
    },
    //排序
    compare: function(x, y) { //比较函数
        if (x < y) {
            return -1;
        } else if (x > y) {
            return 1;
        } else {
            return 0;
        }
    },
    //{key:Array}的形式数据排序，依赖compare方法
    keyArraySort: function(obj) {
        var keys_array = Object.keys(obj).sort(this.compare);
        var sort_obj = {};
        for (var keys = 0; keys < keys_array.length; keys++) {
            sort_obj[keys_array[keys]] = obj[keys_array[keys]].sort(this.compare);
        }
        return sort_obj;
    },
    //{key:obj}的形式数据排序，依赖compare方法
    keyObjSort: function(obj) {
        var keys_array = Object.keys(obj).sort(this.compare);
        var sort_obj = {};
        for (var keys = 0; keys < keys_array.length; keys++) {
            var keys_son_array = Object.keys(obj[keys_array[keys]]).sort(this.compare);
            sort_obj[keys_array[keys]] = {};
            for (var keys_son = 0; keys_son < keys_son_array.length; keys_son++) {
                sort_obj[keys_array[keys]][keys_son_array[keys_son]] = obj[keys_array[keys]][keys_son_array[keys_son]];
            }
        }
        return sort_obj;
    },
    getTransform: function(keyframes) {
        var transform = "transition-timing-function:ease-out;transform:" + keyframes + ";-webkit-transform" + keyframes + ";-ms-transform:" + keyframes + ";-moz-transform:" + keyframes + ";-o-transform:" + keyframes;
        return transform;
    },
    highlight: function (myData, t) {
        t = t.replace(/[`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘’，。、]/im, "");
        var myData = myData;
        var textArray = "";
        var matching = "";
        var num = 1;
        if (t && this.itype != 1 && this.itype != 3) {
            for (var i = 0; i < t.length; i++) {
                if (textArray.indexOf(t[i]) > 0) {
                    continue
                }
                textArray += (i === 0) ? "(" + t[i] + ")" : "|(" + t[i] + ")";
                matching += "$" + num;
                num++;
            }
            if (myData) {
                for (var z = 0; z < myData.length; z++) {
                    myData[z].name = myData[z].name.replace(RegExp(textArray, "gi"), "<span>" + matching + "</span>");
                }
            }
        } else {
            if (myData) {
                for (var z = 0; z < myData.length; z++) {
                    myData[z].name = myData[z].name.replace(t.toUpperCase(), "<span>" + t.toUpperCase() + "</span>");
                }
            }
        }
        return myData;
    },
    touchListener: function(options, touch_region, obj) {
        var touch_region = document.getElementById(touch_region);//鼠标执行区域对象
        var obj = document.getElementById(obj);//动画所被执行对象
        var options = {
            "just":options.just || "",//配置正方向的动画
            "negative":options.negative || "",//配置反方向的动画
            "aspect":options.aspect || "x",//配置监听轴
            "min_distance":options.min_distance || "30",//配置最小可执行范围
            "isDo":options.isDo || false//是否预先执行
        };
        var _this = this;
        if(options.isDo){
            obj.setAttribute("style",_this.getTransform(options.negative));
        }
        switch(options.aspect){
            case "x":
                var x_1,x_2;
                if(('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch){//判断是否支持触点功能
                    touch_region.ontouchstart = function(event){
                        x_1 = event.targetTouches[0].clientX;
                    }
                    touch_region.ontouchend = function(event){
                        x_2 = x_1 - event.changedTouches[0].clientX;
                        if(Math.abs(x_2) > options.min_distance){
                            if(x_2 > 0){
                                obj.setAttribute("style",_this.getTransform(options.just));
                            }else{
                                obj.setAttribute("style",_this.getTransform(options.negative));
                            }
                        }
                    }
                }else{
                    touch_region.onscroll = function(){}
                }
            break;
            case "y":
                var y_1,y_2;
                if(('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch){//判断是否支持触点功能
                    touch_region.ontouchstart = function(event){
                        y_1 = event.targetTouches[0].clientY;
                    }
                    touch_region.ontouchend = function(event){
                        y_2 = y_1 - event.changedTouches[0].clientY;
                        if(Math.abs(y_2) > options.min_distance){
                            if(y_2 > 0){
                                obj.setAttribute("style",_this.getTransform(options.just));
                            }else{
                                obj.setAttribute("style",_this.getTransform(options.negative));
                            }
                        }
                    }
                }else{
                    y_1 = 0;
                    document.onscroll = function(){
                        if(window.scrollY > y_1){
                             obj.setAttribute("style",_this.getTransform(options.just));
                        }else{
                            obj.setAttribute("style",_this.getTransform(options.negative));
                        }
                        y_1 = window.scrollY;
                    }
                }
            break;
        }
    },
};

privateFun.logic_screenPx();

window.onresize = function() {
    if (window.orientation) {
        st = setTimeout("privateFun.logic_screenPx()", 150);
    } else {
        privateFun.logic_screenPx();
    }
};

    